package com.irdstudio.tdp.console.api.rest;

import com.irdstudio.tdp.console.service.facade.SAgentInfoService;
import com.irdstudio.tdp.console.service.vo.BatBatchInfoConfigVO;
import com.irdstudio.tdp.console.service.vo.SAgentInfoVO;
import com.irdstudio.sdk.beans.core.util.StringUtil;
import com.irdstudio.sdk.ssm.util.AgentApiUtil;
import com.irdstudio.sdk.ssm.web.AbstractController;
import com.irdstudio.tdp.console.service.facade.BatBatchInfoConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/api")
public class BatchLogController extends AbstractController {

	@Autowired
	@Qualifier("batchConfigService")
	private BatBatchInfoConfigService batBatchInfoConfigService;

	@Autowired
	@Qualifier("sAgentInfoService")
	private SAgentInfoService sAgentInfoService;

	@RequestMapping(value="/batch/logs/run/{batchId}", method= RequestMethod.GET)
	public @ResponseBody String getBatchRunLogs(@PathVariable("batchId") String batchId, @RequestParam("batchSerialNo") String batchSerialNo) {
		String output = "";
		try{
			//获取代理节点标识
			BatBatchInfoConfigVO batBatchInfoConfigVO = new BatBatchInfoConfigVO();
			batBatchInfoConfigVO.setBatchId(batchId);
			batBatchInfoConfigVO = batBatchInfoConfigService.queryByPk(batBatchInfoConfigVO);
			if(Objects.isNull(batBatchInfoConfigVO)){
				throw new Exception("通过批次号获取批次信息配置信息为空，批次号为:" +batchId);
			}
			String agentId = batBatchInfoConfigVO.getAgentId();
			//获取代理节点地址
			SAgentInfoVO sAgentInfoVO = new SAgentInfoVO();
			sAgentInfoVO.setAgentId(agentId);
			sAgentInfoVO = sAgentInfoService.queryByPk(sAgentInfoVO);
			if(Objects.isNull(sAgentInfoVO)){
				throw new Exception("通过代理节点标识获取代理节点信息为空，代理节点标识为:" +agentId);
			}
			String agentUrl = sAgentInfoVO.getAgentUrl();
			if(StringUtil.isNullorBank(agentUrl)){
				throw new Exception("代理节点地址为空，代理节点标识为:" +agentId);
			}
			//获取批次日志信息
			output = AgentApiUtil.getBatchLogs(agentUrl, batchId);

		}catch (Exception e){
			e.printStackTrace();
			output = "获取批次监控日志失败，原因：" + e.getMessage();
		}
		return output;
	}

}
